package com.hongdee.scm.saleorder.service.impl;

import com.hongdee.common.dao.IHibernateDao;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.common.service.impl.Common;
import com.hongdee.scm.invioce.entity.TCrmCarInvoice;
import com.hongdee.scm.monthlybalance.service.ITScmMonthlyBalanceService;
import com.hongdee.scm.saleorder.dao.ITScmSaleOrderDao;
import com.hongdee.scm.saleorder.entity.TScmSaleOrder;
import com.hongdee.scm.saleorder.entity.TScmSaleOrderDetail;
import com.hongdee.scm.saleorder.service.ITScmSaleOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mr. Xu on 2017/5/14.
 */
@Service
public class TScmSaleOrderServiceImpl implements ITScmSaleOrderService {
    @Autowired
    private ITScmSaleOrderDao itScmSaleOrderDao;
    @Autowired
    private ITScmMonthlyBalanceService itScmMonthlyBalanceService;
    @Autowired
    private IHibernateDao iHibernateDao;
    private String tabName = "T_Scm_Sale_Order";
    //车系对照表
    private String tabCarSeries = "t_bc_car_series";
    //车型对照表
    private String tabCarModel = " t_bc_carmodel";
    //配置对照表
    private String tabCarConfig = "t_bc_carconfigure";
    //外观对照表
    private String tabCarAppearance = "t_scm_appearance";
    //内饰对照表
    private String tabCarTrim = "t_scm_interior";

    /**
     * 销售单分页
     *
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map page(Map data, String start, String limit, String uid,String status) throws Exception {

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select p.id,p.invoice_date,p.vin,p.car_id,p.invoice_header,p.invoice_num,p.invoice_price,p.status,p.contact_phone,p.certificates_num," +
                " p.birthday,p.sale_order_price,p.saler,FROM_UNIXTIME(p.create_time/1000,'%Y-%m-%d') create_time," +
                "u.u_name,tsc.car_series carSeriesName,tsc.car_model carModel,tsc.configure configureName," +
                "tsc.appearance_name,tsc.trim_name interiorName,p.sale_status," +
                "case when p.out_count = 0 then '0' when p.out_count<p.car_count then '2' when p.out_count=p.car_count then '1' end out_status,w.warehouse_name, " +
                "CASE WHEN func_ifPrint(p.id) = 1 THEN '已打印' WHEN func_ifPrint(p.id) =0 THEN '未打印' END print_type")
                .append(" from " + tabName + " p  " +
                        "left join t_bc_user u on u.id = p.create_user" )
                .append(" left join t_scm_car tsc on p.car_id = tsc.id" +
                        " left join t_scm_warehouse w on w.id = p.warehouse")
                .append(" where p.company_id = ?");
        params.add(TokenUtil.getCompanyId(uid));
        //车系
        if (data.get("carSeriesCode") != null && !data.get("carSeriesCode").equals("")) {
            sql.append(" and tsc.car_series_id = ? ");
            params.add(data.get("carSeriesCode"));
            //**车型代码
            if (data.get("carModelCode") != null && !data.get("carModelCode").equals("")) {
                sql.append(" and tsc.car_model_id = ? ");
                params.add(data.get("carModelCode"));
                //**车辆配置
                if (data.get("carConfigureCode") != null && !data.get("carConfigureCode").equals("")) {
                    sql.append(" and tsc.configure_id = ?");
                    params.add(data.get("carConfigureCode"));

                }
            }
        }
        //销售日期起saleDateStart
        if (data.get("saleDateStart") != null && !data.get("saleDateStart").equals("")) {
            sql.append(" and FROM_UNIXTIME(p.create_time/1000,'%Y-%m-%d')>=  ? ");
            params.add(data.get("saleDateStart"));
        }
        //销售日期至saleDateStop
        if (data.get("saleDateStop") != null && !data.get("saleDateStop").equals("")) {
            sql.append(" and p.FROM_UNIXTIME(p.create_time/1000,'%Y-%m-%d') <=  ? ");
            params.add(data.get("saleDateStop"));
        }
        //开票日期起invoiceDateStart
        if (data.get("invoiceDateStart") != null && !data.get("invoiceDateStart").equals("")) {
            sql.append(" and p.invoice_date >=  ? ");
            params.add(data.get("invoiceDateStart"));
        }
        //开票日期至invoiceDateStop
        if (data.get("invoiceDateStop") != null && !data.get("invoiceDateStop").equals("")) {
            sql.append(" and p.invoice_date <=  ? ");
            params.add(data.get("invoiceDateStop"));
        }
        //车主owner
        if (data.get("owner") != null && !data.get("owner").equals("")) {
            sql.append(" and (p.invoice_header like ? )");
            params.add("%" + data.get("owner") + "%");
        }
        //vin
        if (data.get("vin") != null && !data.get("vin").equals("")) {
            sql.append(" and EXISTS (select vin from t_scm_sale_order_detail d where vin like ? and d.sale_order_id = p.id ) ");
            params.add("%" + data.get("vin") + "%");
        }
        //开票状态status
        /*if (data.get("status") != null && !data.get("status").equals("")) {
            sql.append(" and p.finance_type =  ? ");
            params.add(data.get("status"));
        }*/
        //发票号invoiceNum
        if (data.get("invoiceNum") != null && !data.get("invoiceNum").equals("")) {
            sql.append(" and p.invoice_num like  ? ");
            params.add("%" + data.get("invoiceNum") + "%");
        }
        //作废状态
        if (data.get("status") != null && !data.get("status").equals("")) {
            sql.append(" and p.status =  ? ");
            params.add(data.get("status"));
        }
        if(data.get("printType") != null && !data.get("printType").equals("")){
            //1已打印 0未打印
            sql.append(" and func_ifPrint (p.id) =  ? ");
            params.add(data.get("printType"));
        }
        sql.append(" order by p.create_time desc ");
        return this.itScmSaleOrderDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 销售车辆管理
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map pageCar(Map data, String start, String limit, String uid) throws Exception{

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select d.*,p.car_model model_name,p.configure configure_name,p.brand,d.sale_order_price invoice_price," +
                "DATE_FORMAT(p.purchase_date, '%Y-%m-%d') purchase_date1,p.engine_num,p.financial_belong,"+
                "w.warehouse_name,p.certificate_num,date_format(p.enter_warehouse_date_start,'%Y-%m-%d') enterWarehouseDateStart,p.sale_type "+
                "from t_scm_sale_order_detail d " +
                "inner join t_scm_car p on p.id = d.car_id "+
                "LEFT JOIN t_scm_warehouse w ON w.id = d.warehouse where d.status = '0' and d.company_id = ?");
        params.add(TokenUtil.getCompanyId(uid));

        //vin查询
        if(data.get("vin")!=null&&!data.get("vin").toString().equals("")){
            sql.append(" and d.vin like ? ");
            params.add("%"+data.get("vin")+"%");
        }

        //车型代码
        if (data.get("carModelCode") != null && !data.get("carModelCode").equals("")) {
            sql.append(" and p.car_model_id = ? ");
            params.add(data.get("carModelCode"));
        }

        //销售日期起
        if(data.get("saleDateStart")!=null && !data.get("saleDateStart").equals("")){
            sql.append(" and DATE_FORMAT(p.sale_date,'%Y-%m-%d') >= ?");
            params.add(data.get("saleDateStart"));
        }
        //销售日期到
        if(data.get("saleDateStop")!=null && !data.get("saleDateStop").equals("")){
            sql.append(" and DATE_FORMAT(d.sale_date,'%Y-%m-%d') <= ?");
            params.add(data.get("saleDateStop"));
        }
        return this.itScmSaleOrderDao.page(sql.toString(), params.toArray(), start, limit);
    }
    /**
     * 保存修改
     *
     * @param data
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public void saveOrUpdate(TScmSaleOrder data, String uid) throws Exception {

        //id为空时则为添加
        if (data.getId() == null) {
            if(this.ifExistInvoice(data.getInvoiceNum(),uid)){
                throw new Exception("该销售发票已存在！");
            }
            //默认未月结
            data.setMonthlyStatus("0");
            //默认已保存状态(0未出库1已出库)
            data.setSaleStatus("0");
            data.setCreateUser(uid);
            //0正常1作废
            data.setStatus("0");
            data.setCreateTime(Calendar.getInstance().getTimeInMillis());
            data.setCarCount("1");
            //更新车辆销售状态
            this.itScmSaleOrderDao.executeSQL("update t_scm_car set sale_type = '2',sale_price = ?,sale_date=? where id = ? ", data.getInvoicePrice(),data.getInvoiceDate(),data.getCarId());
            //更新车辆调拨状态
            this.itScmSaleOrderDao.executeSQL("update t_scm_stock set allocation_status='1' where car_id = ? ", data.getCarId());

        } else {
            if(this.itScmMonthlyBalanceService.ifMonthlyBalance(TokenUtil.getCompanyId(uid),new SimpleDateFormat("yyyy-MM-dd").parse(data.getInvoiceDate()))){
               throw new Exception("已月结不能修改销售价格");
            }

            //id不为空时则为修改
            data.setUpdateUser(uid);
            data.setUpdateTime(Calendar.getInstance().getTimeInMillis());
        }
        data.setCompanyId(TokenUtil.getCompanyId(uid));
        data.setOutCount("0");//出库车辆数量
        this.itScmSaleOrderDao.saveOrUpdate(data);
        Map map = new HashMap();
        map.put("saleOrderPrice",data.getSaleOrderPrice());
        map.put("equipmentPrice",data.getEquipmentPrice());
        map.put("exsurancePrice",data.getExsurancePrice());
        map.put("agencyPrice",data.getAgencyPrice());
        map.put("otherPrice",data.getOtherPrice());
        map.put("warehouse",data.getWarehouse());
        map.put("vin",data.getVin());
        map.put("carId",data.getCarId());
        map.put("saleOrderId",data.getId());
        map.put("invoiceDate",data.getInvoiceDate());
        map.put("configureId",data.getConfigureId());
        map.put("carSeriesId",data.getCarSeriesId());
        map.put("carModelId",data.getCarModelId());
        map.put("appearanceCode",data.getAppearanceCode());
        map.put("trimCode",data.getTrimCode());
        map.put("firstEnterWarehouseDate",data.getFirstEnterWarehouseDate());
        this.saveSaleDetail(map,uid,data.getId());
    }

    /**
     * 一单多车保存
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void saveSaleOrder(Map data, String uid) throws Exception{

        TScmSaleOrder tScmSaleOrder = new TScmSaleOrder();
        Map saleOrderMap = (Map) data.get("saveSale");

        //销售单
        if(saleOrderMap.get("invoiceNum")!=null&&!saleOrderMap.get("invoiceNum").equals("")){//发票号
            if(this.ifExistInvoice(saleOrderMap.get("invoiceNum").toString(),uid)){
                throw new Exception("该销售发票已存在！");
            }
            tScmSaleOrder.setInvoiceNum(saleOrderMap.get("invoiceNum").toString());
        }
        if(saleOrderMap.get("saleOrderNum")!=null&&!saleOrderMap.get("saleOrderNum").equals("")){//销售单编号
            tScmSaleOrder.setSaleOrderNum(saleOrderMap.get("saleOrderNum").toString());
        }
        if(saleOrderMap.get("invoicePrice")!=null&&!saleOrderMap.get("invoicePrice").equals("")){//发票价格
             tScmSaleOrder.setInvoicePrice(saleOrderMap.get("invoicePrice").toString());
        }
        if(saleOrderMap.get("saler")!=null&&!saleOrderMap.get("saler").equals("")){//销售专员
           tScmSaleOrder.setSaler(saleOrderMap.get("saler").toString());
        }
        if(saleOrderMap.get("customerName")!=null&&!saleOrderMap.get("customerName").equals("")){//客户姓名
           tScmSaleOrder.setCustomerName(saleOrderMap.get("customerName").toString());
        }
        if(saleOrderMap.get("contactPhone")!=null&&!saleOrderMap.get("contactPhone").equals("")){//联系电话
            tScmSaleOrder.setContactPhone(saleOrderMap.get("contactPhone").toString());
        }
        if(saleOrderMap.get("owenPhone")!=null&&!saleOrderMap.get("owenPhone").equals("")){//车主联系电话
            tScmSaleOrder.setOwenPhone(saleOrderMap.get("owenPhone").toString());
        }
        if(saleOrderMap.get("birthday")!=null&&!saleOrderMap.get("birthday").equals("")){//出生日期
            tScmSaleOrder.setBirthday(saleOrderMap.get("birthday").toString());
        }
        if(saleOrderMap.get("certificatesNum")!=null&&!saleOrderMap.get("certificatesNum").equals("")){//证件号码
           tScmSaleOrder.setCertificatesNum(saleOrderMap.get("certificatesNum").toString());
        }
        if(saleOrderMap.get("invoiceDate")!=null&&!saleOrderMap.get("invoiceDate").equals("")){//开票日期
           tScmSaleOrder.setInvoiceDate(saleOrderMap.get("invoiceDate").toString());
        }
        if(saleOrderMap.get("payType")!=null&&!saleOrderMap.get("payType").equals("")){//付款方式
           tScmSaleOrder.setPayType(saleOrderMap.get("payType").toString());
        }
        if(saleOrderMap.get("payNum")!=null&&!saleOrderMap.get("payNum").equals("")){//付款账号
           tScmSaleOrder.setPayNum(saleOrderMap.get("payNum").toString());
        }
        if(saleOrderMap.get("invoiceHeader")!=null&&!saleOrderMap.get("invoiceHeader").equals("")){//发票抬头
           tScmSaleOrder.setInvoiceHeader(saleOrderMap.get("invoiceHeader").toString());
        }
        if(saleOrderMap.get("carCount")!=null&&!saleOrderMap.get("carCount").equals("")){//数量
           tScmSaleOrder.setCarCount(saleOrderMap.get("carCount").toString());
        }

        if(saleOrderMap.get("id")==null||saleOrderMap.get("id").equals("")){//新增
            tScmSaleOrder.setCreateUser(uid);
            tScmSaleOrder.setCreateTime(Calendar.getInstance().getTimeInMillis());
            tScmSaleOrder.setMonthlyStatus("0");//0未月结1已月结
            tScmSaleOrder.setCompanyId(TokenUtil.getCompanyId(uid));
            tScmSaleOrder.setStatus("0");//0不作废1已作废
            tScmSaleOrder.setSaleStatus("0");//0未出库1已出库
            tScmSaleOrder.setInvoiceStatus("0");//开票状态
            tScmSaleOrder.setOutCount("0");//出库车辆数量
        }else{//修改
            if(this.itScmMonthlyBalanceService.ifMonthlyBalance(TokenUtil.getCompanyId(uid),new SimpleDateFormat("yyyy-MM-dd").parse(saleOrderMap.get("invoiceDate").toString()))){
                throw new Exception("已月结不能修改销售价格");
            }
            tScmSaleOrder.setUpdateUser(uid);
            tScmSaleOrder.setCompanyId(TokenUtil.getCompanyId(uid));
            tScmSaleOrder.setUpdateTime(Calendar.getInstance().getTimeInMillis());
            TScmSaleOrder tt = (TScmSaleOrder) this.iHibernateDao.findEntity(TScmSaleOrder.class,saleOrderMap.get("id").toString());
            tScmSaleOrder.setId(tt.getId());
            tScmSaleOrder.setStatus(tt.getStatus());
            tScmSaleOrder.setInvoiceStatus(tt.getInvoiceStatus());
            tScmSaleOrder.setOutCount(tt.getOutCount());
            tScmSaleOrder.setSaleStatus(tt.getSaleStatus());
            tScmSaleOrder.setMonthlyStatus(tt.getMonthlyStatus());
            tScmSaleOrder.setCreateTime(tt.getCreateTime());
            tScmSaleOrder.setCreateUser(tt.getCreateUser());
        }
        this.itScmSaleOrderDao.saveOrUpdate(tScmSaleOrder);
        //存车辆明细
        this.saveSaleDetail(data,uid,tScmSaleOrder.getId());
    }

    /**
     * 存车辆明细
     * @param data
     * @param uid
     * @param saleId
     * @throws Exception
     */
    private void saveSaleDetail(Map data,String uid,String saleId) throws Exception{

        List<Map> saleOrderList = new ArrayList<>();
        Map saleMap = new HashMap<>();
        if(data.get("saleOrderList")==null){//单个车
            saleOrderList.add(data);
            saleMap.put("invoiceDate",data.get("invoiceDate"));
        }else{//多个车
          saleOrderList  = (ArrayList) data.get("saleOrderList");
          saleMap  = (Map) data.get("saveSale");
        }

        for(Map sol:saleOrderList){
            TScmSaleOrderDetail tScmSaleOrderDetail = new TScmSaleOrderDetail();
            if(sol.get("saleOrderPrice")!=null&&!sol.get("saleOrderPrice").equals("")){//销售价格
                tScmSaleOrderDetail.setSaleOrderPrice(sol.get("saleOrderPrice").toString());
            }
            if(sol.get("equipmentPrice")!=null&&!sol.get("equipmentPrice").equals("")){//装具价格
                tScmSaleOrderDetail.setEquipmentPrice(sol.get("equipmentPrice").toString());
            }
            if(sol.get("exsurancePrice")!=null&&!sol.get("exsurancePrice").equals("")){//延保价格
               tScmSaleOrderDetail.setExsurancePrice(sol.get("exsurancePrice").toString());
            }
            if(sol.get("agencyPrice")!=null&&!sol.get("agencyPrice").equals("")){//代办价格
                tScmSaleOrderDetail.setAgencyPrice(sol.get("agencyPrice").toString());
            }
            if(sol.get("otherPrice")!=null&&!sol.get("otherPrice").equals("")){//其他价格
               tScmSaleOrderDetail.setOtherPrice(sol.get("otherPrice").toString());
            }
            if(sol.get("carId")!=null&&!sol.get("carId").equals("")){//car_id
               tScmSaleOrderDetail.setCarId(sol.get("carId").toString());
            }
            if(sol.get("vin")!=null&&!sol.get("vin").equals("")){//vin
               tScmSaleOrderDetail.setVin(sol.get("vin").toString());
            }
            if(sol.get("warehouse")!=null&&!sol.get("warehouse").equals("")){//仓库
               tScmSaleOrderDetail.setWarehouse(sol.get("warehouse").toString());
            }
            if(sol.get("configureId")!=null&&!sol.get("configureId").equals("")){//配置
                tScmSaleOrderDetail.setConfigureId(sol.get("configureId").toString());
            }
            if(sol.get("carModelId")!=null&&!sol.get("carModelId").equals("")){//车型id
                tScmSaleOrderDetail.setCarModelId(sol.get("carModelId").toString());
            }
            if(sol.get("carSeriesId")!=null&&!sol.get("carSeriesId").equals("")){//车系id
                tScmSaleOrderDetail.setCarSeriesId(sol.get("carSeriesId").toString());
            }
            if(sol.get("appearanceCode")!=null&&!sol.get("appearanceCode").equals("")){//外观代码
                tScmSaleOrderDetail.setAppearanceCode(sol.get("appearanceCode").toString());
            }
            if(sol.get("trimCode")!=null&&!sol.get("trimCode").equals("")){//内饰代码
                tScmSaleOrderDetail.setTrimCode(sol.get("trimCode").toString());
            }
            if(sol.get("firstEnterWarehouseDate")!=null&&!sol.get("firstEnterWarehouseDate").equals("")){//内饰代码
                tScmSaleOrderDetail.setFirstEnterWarehouseDate(sol.get("firstEnterWarehouseDate").toString());
            }
            tScmSaleOrderDetail.setCompanyId(TokenUtil.getCompanyId(uid));
            tScmSaleOrderDetail.setSaleOrderId(saleId);//销售单id
            List list = this.itScmSaleOrderDao.list("select * from t_scm_sale_order_detail where sale_order_id=? and vin =? and company_id =? and status = '0'",saleId,sol.get("vin"),TokenUtil.getCompanyId(uid));
            if(list.size()==0||list==null){//新增
                tScmSaleOrderDetail.setCreateUser(uid);
                tScmSaleOrderDetail.setCreateTime(Calendar.getInstance().getTimeInMillis());
                tScmSaleOrderDetail.setStatus("0");//0不作废1已作废
                //更新车辆销售状态
                this.itScmSaleOrderDao.executeSQL("update t_scm_car set sale_type = '2',sale_date=? where id = ? ", saleMap.get("invoiceDate"),tScmSaleOrderDetail.getCarId());
                //更新车辆调拨状态
                this.itScmSaleOrderDao.executeSQL("update t_scm_stock set allocation_status='1' where car_id = ? ", tScmSaleOrderDetail.getCarId());
            }else{//修改
                String id = ((Map)list.get(0)).get("id").toString();
                tScmSaleOrderDetail.setUpdateUser(uid);
                tScmSaleOrderDetail.setUpdateTime(Calendar.getInstance().getTimeInMillis());
                TScmSaleOrderDetail tt = (TScmSaleOrderDetail) this.iHibernateDao.findEntity(TScmSaleOrderDetail.class,id);
                tScmSaleOrderDetail.setId(tt.getId());
                tScmSaleOrderDetail.setCompanyId(TokenUtil.getCompanyId(uid));
                tScmSaleOrderDetail.setStatus(tt.getStatus());
                tScmSaleOrderDetail.setTrimCode(tt.getTrimCode());
                tScmSaleOrderDetail.setAppearanceCode(tt.getAppearanceCode());
                tScmSaleOrderDetail.setCarSeriesId(tt.getCarSeriesId());
                tScmSaleOrderDetail.setCarModelId(tt.getCarModelId());
                tScmSaleOrderDetail.setCarSeriesId(tt.getCarSeriesId());
                tScmSaleOrderDetail.setFirstEnterWarehouseDate(tt.getFirstEnterWarehouseDate());
                tScmSaleOrderDetail.setCreateTime(tt.getCreateTime());
                tScmSaleOrderDetail.setCreateUser(tt.getCreateUser());
            }
            this.itScmSaleOrderDao.saveOrUpdate(tScmSaleOrderDetail);
        }

    }

    /**
     * b保存时查看销售发票是否重复
     * @param invoiceNum
     * @return
     * @throws Exception
     */
    private boolean ifExistInvoice(String invoiceNum,String uid) throws Exception{

        List list = this.itScmSaleOrderDao.list("select * from t_scm_sale_order where invoice_num = ? and status = '0' " +
                "and company_id =?",invoiceNum,TokenUtil.getCompanyId(uid));
        if(list.size()>0){
            return true;
        }
        return false;
    }
    /**
     * 销售单作废
     * @param uid
     * @param id
     * @throws Exception
     */
    @Override
    public void saleOrderCancel (String uid,String id ) throws Exception{
        if(!id.isEmpty()){

            int rs =  this.itScmSaleOrderDao.executeSQL("update "+tabName+ " set status = '1' where id = ?  and  status<>'1' ",id);

            if (0== rs) {//已作废数据
                return;
            }

            //更新车辆销售状态
            this.itScmSaleOrderDao.executeSQL("update t_scm_car set sale_type='1',sale_date='' where id in (select car_id from t_scm_sale_order_detail where sale_order_id=?) ", id);
            //更新销售车辆明细的状态
            this.itScmSaleOrderDao.executeSQL("update t_scm_sale_order_detail set status='1' where sale_order_id=?",id);
            String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            this.itScmSaleOrderDao.executeSQL("update t_scm_sale_order set status = '1',cancel_time=?,out_count='0' where id =?",time,id);
            //更新车辆调拨状态
            if(this.itScmSaleOrderDao.info("select * from T_Scm_OutWareHouse where car_id in (select car_id from t_scm_sale_order_detail where sale_order_id=?) and out_status='0'",id).size()>0){
                this.itScmSaleOrderDao.executeSQL("update t_scm_stock set allocation_status='0',enter_type='2' where car_id in (select car_id from t_scm_sale_order_detail where sale_order_id=?) ", id);
            }
            //更新车辆待回库状态
            this.itScmSaleOrderDao.executeSQL("update T_Scm_OutWareHouse set out_status=(case when out_status='0' then '-1' else '1' end)," + ///不需要再出库
                    " need_back='0' where car_id in (select car_id from t_scm_sale_order_detail where sale_order_id=?) and out_status <>'2' ", id);

            //更新车辆销售状态
            this.itScmSaleOrderDao.executeSQL("update t_scm_invoice_price set invoices_type='-5' where invoices_type='5' " +
                    "and car_id in (select car_id from t_scm_sale_order_detail where sale_order_id=?) ", id);

            //UPDATE T_Scm_Car_Price_Detail SET sale_price=?, out_date=?,out_type=(case when buy_price is null then 1 else 2 end) WHERE car_id=? and out_date is null
            this.itScmSaleOrderDao.executeSQL("update T_Scm_Car_Price_Detail SET out_date=NULL,out_type=0 where  " +
                    " car_id in (select car_id from t_scm_sale_order_detail where sale_order_id=?) ", id);
        }else {
            throw new Exception("请选择销售单");
        }

    }

    /**
     * 销售单详细
     *
     * @param id
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map info(String id, String uid) throws Exception {
        List params = new ArrayList();
        //String sql = "select p.*,cm.model_name from " + tabName + " p left join t_bc_carmodel cm on cm.id = p.car_model_code  where p.id = ? and p.company_id= ?";
        StringBuffer sqlInfo = new StringBuffer();
        sqlInfo.append("select p.*,tsc.car_series carSeriesName,tsc.car_model modelName,tsc.configure configureName," +
                " tsc.appearance_name,tsc.trim_name interiorName")
                .append(" from " + tabName + " p  left join t_scm_car tsc on p.vin = tsc.vin   where p.id = ? and p.company_id= ?");
        params.add(id);
        params.add(TokenUtil.getCompanyId(uid));
        return this.itScmSaleOrderDao.info(sqlInfo.toString(), params.toArray());
    }

    /**
     * 销售发票查看详情
     * @param id
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map infoCar(String id,String uid) throws Exception{

        List<Map<String,Object>> list = this.itScmSaleOrderDao.list("select d.*,c.configure configureName,c.car_model modelName," +
                "c.car_series,c.appearance_name,c.trim_name,d.warehouse " +
                "from t_scm_sale_order_detail d " +
                "inner join t_scm_car c on c.id = d.car_id " +
                "where d.sale_order_id =?",id);
        Map saleOrder = this.itScmSaleOrderDao.info("select * from t_scm_sale_order where id=?",id);

        Map mapData = new HashMap();
        mapData.put("saleOrder",saleOrder);
        mapData.put("saleList",list);
        return mapData;
    }

    /*
     * 配车接口，待完善
     *
     * @param data
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map configCar(TScmSaleOrder data, String uid) throws Exception {
        List params = new ArrayList();
        StringBuffer sql = new StringBuffer();
        sql.append("select * from T_Scm_Car where company_id = ? ");
        params.add(TokenUtil.getCompanyId(uid));
        sql.append(" limit 1 ");
        return this.itScmSaleOrderDao.info(sql.toString(), params.toArray());
    }

    /**
     * 查询车辆成本（无发票取暂估金额，反之取发票金额）
     *
     * @param vin
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map carCost(String vin, String uid) throws Exception {
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append("select invoice_price,estimate_price from T_scm_car where vin = ? and company_id=?");
        List list = this.itScmSaleOrderDao.list(sqlBuf.toString(), vin,TokenUtil.getCompanyId(uid));
        Map map = (Map) list.get(0);
        Map temp = new HashMap();
        //发票金额不存在，取暂估
        if (map.get("invoicePrice") == null || StringUtils.isEmpty(map.get("invoicePrice"))) {
            temp.put("carCost", map.get("estimatePrice"));
        } else {
            temp.put("carCost", map.get("invoicePrice"));
        }
        return temp;
    }

    /**
     * 查询多个车辆成本（无发票取暂估金额，反之取发票金额）
     * @param vins
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public List carCostMore(String[] vins ,String uid) throws Exception{

        Common common = new Common();
        Boolean hasWhere = false;
        List params = new ArrayList();
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append("select invoice_price,estimate_price from T_scm_car ");
        if(vins.length>0){
          hasWhere = common.appendWhereIfNeed(sqlBuf, hasWhere);
          sqlBuf.append(" vin in ( ");
          for (String vin : vins) {
              sqlBuf.append(" ? , ");
              params.add(vin);
          }
            sqlBuf.append(" '' ) ");
        }
        sqlBuf.append(" and company_id=?");
        params.add(TokenUtil.getCompanyId(uid));
        List<Map<String,Object>> list = this.itScmSaleOrderDao.list(sqlBuf.toString(),params.toArray());
        List priceList = new ArrayList();
        for(Map<String,Object> map:list){
            Map temp = new HashMap();
            //发票金额不存在，取暂估
            if (map.get("invoicePrice") == null || StringUtils.isEmpty(map.get("invoicePrice"))) {
                temp.put("carCost", map.get("estimatePrice"));
            } else {
                temp.put("carCost", map.get("invoicePrice"));
            }
            priceList.add(temp);
        }
        return priceList;
    }

    /**
     * 添加到销售单数据库表
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public boolean createBySaleInvoice(TCrmCarInvoice data) throws Exception{


       if(this.itScmSaleOrderDao.info("select * from t_scm_sale_order where invoice_num=?",data.getFPHM()).size()<=0) {

        }else{
           return true;
       }

        TScmSaleOrder entity = new TScmSaleOrder();
        TScmSaleOrderDetail tScmSaleOrderDetail = new TScmSaleOrderDetail();

        entity.setInvoiceNum(data.getFPHM());
        entity.setInvoiceDate(data.getGZRQ());
        entity.setInvoiceHeader(data.getGHDW());
        entity.setCreateTime(Calendar.getInstance().getTimeInMillis());
        tScmSaleOrderDetail.setCreateTime(Calendar.getInstance().getTimeInMillis());
        ////车主信息
        entity.setOwenName(data.getGHDW());
        entity.setCustomerName(data.getGHDW());
        //发票价格
        entity.setInvoicePrice(data.getDJ());
        //销售专员
        entity.setSaler(data.getSKR());
        //vin
        entity.setVin(data.getCJHM());
        tScmSaleOrderDetail.setVin(data.getCJHM());
        //联系电话
        entity.setContactPhone(data.getSJDH());
        //车主联系电话
        entity.setOwenPhone(data.getLXDH());
        //证件号码
        entity.setCertificatesNum(data.getSFZHM());
        //销售状态(0未出库1已出库)
        entity.setSaleStatus("0");
        entity.setStatus("0");
        tScmSaleOrderDetail.setStatus("0");
        //付款账号
        entity.setPayNum(data.getYHZH());
        entity.setMonthlyStatus("0");
        entity.setOutCount("0");
        entity.setCarCount("1");

        //车辆信息:取最后添加车辆的公司车辆信息
        List carList = new ArrayList();
        if(data.getCompanyId()!=null&&!data.getCompanyId().equals("")){
            carList = this.itScmSaleOrderDao.list("select p.*,s.warehouse_id from t_scm_car p left join t_scm_stock s on p.vin = s.vin where p.vin=? and p.company_id = ? order by p.create_time desc limit 1",data.getCJHM(),data.getCompanyId());
        }else {
            carList = this.itScmSaleOrderDao.list("select p.*,s.warehouse_id from t_scm_car p left join t_scm_stock s on p.vin = s.vin where p.vin=? order by p.create_time desc limit 1",data.getCJHM());
        }

        Map car = new HashMap();
        if(carList.size()>0){ //有车的时候
            car = (Map) carList.get(0);
        }else{//没车的时候
          tScmSaleOrderDetail.setCompanyId(data.getCompanyId());
          tScmSaleOrderDetail.setStatus("2");
          entity.setCompanyId(data.getCompanyId());
          entity.setSaleStatus("2");
          entity.setStatus("2");
          this.itScmSaleOrderDao.saveOrUpdate(entity);
          tScmSaleOrderDetail.setSaleOrderId(entity.getId());
          this.itScmSaleOrderDao.saveOrUpdate(tScmSaleOrderDetail);
          return true;
        }

       if (car.size() == 0){
           return true;
       }

       //车系id
        if (null != car.get("carSeriesId")) {
            entity.setCarSeriesId(car.get("carSeriesId").toString());
            tScmSaleOrderDetail.setCarSeriesId(car.get("carSeriesId").toString());
        }
        //车型id
        if (null != car.get("carModelId")) {
            entity.setCarModelId(car.get("carModelId").toString());
            tScmSaleOrderDetail.setCarModelId(car.get("carModelId").toString());
        }
        //配置id
        if (null != car.get("configureId")) {
            entity.setConfigureId(car.get("configureId").toString());
            tScmSaleOrderDetail.setConfigureId(car.get("configureId").toString());
        }
        //外观颜色
        if (null != car.get("appearanceCode")) {
            entity.setAppearanceCode(car.get("appearanceCode").toString());
            tScmSaleOrderDetail.setAppearanceCode(car.get("appearanceCode").toString());
        }
        //内饰编号
        if (null != car.get("trimCode")) {
            entity.setTrimCode(car.get("trimCode").toString());
            tScmSaleOrderDetail.setTrimCode(car.get("trimCode").toString());
        }

        //初次入库时间
        if (null != car.get("enterWarehouseDateStart")) {
            entity.setFirstEnterWarehouseDate(car.get("enterWarehouseDateStart").toString());
            tScmSaleOrderDetail.setFirstEnterWarehouseDate(car.get("enterWarehouseDateStart").toString());
        }
        //车辆id
        entity.setCarId(car.get("id").toString());
        tScmSaleOrderDetail.setCarId(car.get("id").toString());
        //车辆仓库
        if (null != car.get("warehouseId")) {
            entity.setWarehouse(car.get("warehouseId").toString());
            tScmSaleOrderDetail.setWarehouse(car.get("warehouseId").toString());
        }

        //状态(0正常1作废2没有这辆车入库)
        if(this.itScmSaleOrderDao.info("select * from t_scm_car where vin =? and status='1' and finance_type in (2,3)",data.getCJHM()).size()<=0){
            tScmSaleOrderDetail.setStatus("2");
            entity.setSaleStatus("2");
            entity.setStatus("2");
        }else{
            tScmSaleOrderDetail.setStatus("0");
            entity.setSaleStatus("0");
            entity.setStatus("0");
        }
        //公司id
        if(data.getCompanyId()==null || data.getCompanyId().equals("")){
            tScmSaleOrderDetail.setCompanyId(car.get("companyId").toString());
            entity.setCompanyId(car.get("companyId").toString());
        }else{
            tScmSaleOrderDetail.setCompanyId(data.getCompanyId());
            entity.setCompanyId(data.getCompanyId());
        }

        this.itScmSaleOrderDao.saveOrUpdate(entity);
        tScmSaleOrderDetail.setSaleOrderId(entity.getId());
        this.itScmSaleOrderDao.saveOrUpdate(tScmSaleOrderDetail);

        ////设置车辆不可销售
        String hql = "update TScmCar set  saleType='2' where id = :carId";
        Map params = new HashMap();
        // params.put("warehouseId", warehouseId);
        //params.put("enterDate",enterDate);
        params.put("carId", car.get("id"));
        this.itScmSaleOrderDao.update(hql, params);


        return true;
    }

    /**
     * 判断扫码添加的销售单中的车辆是否入库(实物入库财务暂估或正入)
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void ifCarIn(Map data,String uid) throws Exception{

        if(data.get("saleOrderId")==null||data.get("saleOrderId").equals("")||data.isEmpty()){
            throw new Exception("请选择销售单!");
        }

        List<String> saleIdList = new ArrayList<>();
        List<Map<String,Object>> vins = new ArrayList<>();
        saleIdList = (List<String>) data.get("saleOrderId");
        boolean flag = false;
        for (String id : saleIdList) {
            vins = this.itScmSaleOrderDao.list("select vin from t_scm_sale_order_detail where sale_order_id =?",id);
        }
        for(Map<String,Object> vin:vins){
            if(this.itScmSaleOrderDao.info("select * from t_scm_car where vin = ? and status = '1' and finance_type in ('2','3')",vin).size()<=0){
                throw new Exception(vin+"该车辆没有入库!");
            }
            flag = true;
        }
        if(flag){
            for (String id : saleIdList) {
                this.itScmSaleOrderDao.executeSQL("update t_scm_sale_order set status = '0' where id=?",id);
            }
        }
    }

    /**
     * 销售车辆已出库的车辆
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map outPageCar(Map data,String start,String limit, String uid) throws Exception{

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select * from (select o.out_date,o.vin,c.car_series,c.car_model,c.configure,w.warehouse_name" +
                " from t_scm_outwarehouse o inner join t_scm_car c on c.id = o.car_id" +
                " left join t_scm_warehouse w on o.out_warehouse_id = w.id where o.company_id = ?" +
                " and o.outType = '1' and out_status = '1' ");
        params.add(TokenUtil.getCompanyId(uid));
        //vin
        if(data.get("vin")!=null&&!"".equals(data.get("vin"))){
            sql.append(" and vin like ? ");
            params.add("%"+data.get("vin")+"%");
        }
        //出库时间
        if(data.get("outDateStart")!=null&&!"".equals(data.get("outDateStart"))){
            sql.append(" and out_date >=?");
            params.add(data.get("outDateStart"));
        }
        if(data.get("outDateStop")!=null&&!"".equals(data.get("outDateStop"))){
            sql.append(" and out_date <=?");
            params.add(data.get("outDateStop"));
        }
        sql.append(" order by o.out_date desc) temp ");
        Map map = this.itScmSaleOrderDao.page(sql.toString(),params.toArray(),start,limit);
        return map;
    }
}
